package icu.xblogs.report.controller;

//import com.sun.xml.internal.bind.v2.runtime.reflect.Lister;
import icu.xblogs.report.domain.AttendanceRecord;
import icu.xblogs.report.domain.Employee;
import icu.xblogs.report.domain.PageAndList;
import icu.xblogs.report.plugin.Page;
import icu.xblogs.report.service.AttendanceRecordService;
import icu.xblogs.report.service.ManagerService;
import icu.xblogs.report.utils.CookieUtil;
import icu.xblogs.report.utils.ExcelUtil;
import icu.xblogs.report.utils.FileConstants;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Frank KONG
 * @version 1.0
 * @date 2020/11/17 10:45
 *
 * 该Controller下请求均需要登录后才可以处理
 */
@Controller
@RequestMapping("/manager")
public class ManagerController {

    private ManagerService managerService;
    private AttendanceRecordService attendanceRecordService;

    @Autowired
    @Qualifier("managerService")
    public void setManagerService(ManagerService managerService) {
        this.managerService = managerService;
    }

    @Autowired
    @Qualifier("attendanceRecordService")
    public void setAttendanceRecordService(AttendanceRecordService attendanceRecordService) {
        this.attendanceRecordService = attendanceRecordService;
    }

    @RequestMapping("/test")
    public void test(){
        System.out.println("manager test...");
    }

    @RequestMapping(value = "/getId", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getId(HttpServletRequest request){
        HashMap<String, String> hashMap = CookieUtil.getCookie(request, "id");
        return hashMap.get("id");
    }

    @RequestMapping(value = "/getAttendanceByDate", produces = "application/json")
    @ResponseBody
    public PageAndList<Map<String, String>> getAttendanceByDate(String date, int num){
        Page page = new Page(10, num);
        List<Map<String, String>> dayList = attendanceRecordService.getDayList(date, page);
        return new PageAndList<>(page, dayList);
    }

    @RequestMapping(value = "/getUnattendanceByDate", produces = "application/json")
    @ResponseBody
    public PageAndList<Map<String, String>> getUnattendanceByDate(String date, int num){
        Page page = new Page(10, num);
        List<Map<String, String>> absenceDayList = attendanceRecordService.getAbsenceDayList(date, page);
        return new PageAndList<>(page, absenceDayList);
    }

    @RequestMapping(value = "/getAttendanceByMonth", produces = "application/json")
    @ResponseBody
    public PageAndList<Map<String, String>> getAttendanceByMonth(String month, int num){
        Page page = new Page(10, num);
        List<Map<String, String>> monthList = attendanceRecordService.getMonthList(month, page);
        return new PageAndList<>(page, monthList);
    }

    @RequestMapping(value = "/getLateByMonth", produces = "application/json")
    @ResponseBody
    public PageAndList<Map<String, String>> getLateByMonth(String month, String time, int num) throws UnsupportedEncodingException {
        time = URLDecoder.decode(time, "UTF-8");
        Page page = new Page(10, num);
        List<Map<String, String>> monthLateList = attendanceRecordService.getMonthLateList(month, time, page);
        return new PageAndList<>(page, monthLateList);
    }

    private void upload(String date, HttpServletResponse response, Workbook workbook, OutputStream output) throws IOException {
        try {
            response.setHeader("Content-disposition", "attachment; filename="+ date +"_report.xls");
            workbook.write(output);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            output.close();
        }
    }

    @RequestMapping(value = "/getReportForDayList", produces = "application/msexcel")
    public void getReportForDayList(String date, HttpServletResponse response) throws IOException {
        List<Map<String, String>> dayList = attendanceRecordService.getDayList(date);
        List<Map<String, String>> absenceList = attendanceRecordService.getAbsenceDayList(date);
        dayList.addAll(absenceList);
        Workbook workbook = ExcelUtil.listToExcel(dayList);
        OutputStream output = response.getOutputStream();
        upload(date, response, workbook, output);
    }

    @RequestMapping(value = "/getReportForMonth", produces = "application/msexcel")
    public void getReportForMonth(String month, HttpServletResponse response) throws IOException {
        List<Map<String, String>> monthList = attendanceRecordService.getMonthList(month);
        Workbook workbook = ExcelUtil.listToExcel(monthList);
        OutputStream output = response.getOutputStream();
        upload(month, response, workbook, output);
    }

    @RequestMapping(value = "/getReportForLate", produces = "application/msexcel")
    public void getReportForLate(String month, String time, HttpServletResponse response) throws IOException {
        List<Map<String, String>> monthLateList = attendanceRecordService.getMonthLateList(month, time);
        Workbook workbook = ExcelUtil.listToExcel(monthLateList);
        OutputStream output = response.getOutputStream();
        upload(month + "_" + time, response, workbook, output);
    }

    @RequestMapping(value = "/modifyPassword", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String modifyPassword(HttpServletRequest request, String oldPassword, String newPassword){
        managerService.updatePsw(Integer.parseInt(CookieUtil.getCookie(request, "id").get("id")), oldPassword, newPassword);
        return "success";
    }

    @RequestMapping(value = "/getAllEmployee", produces = "application/json")
    @ResponseBody
    public PageAndList<Employee> getAllEmployee(int num){
        Page page = new Page(5, num);
        List<Employee> employees = managerService.getAllEmployee(page);
        return new PageAndList<>(page, employees);
    }

    @RequestMapping("/downloadPic")
    public void downloadPicture(String fileName, HttpServletResponse response){
        // 设置下载的响应头信息
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + fileName + ".jpg");
        File imgFile = new File(FileConstants.PIC_PATH + fileName + ".jpg");
        responseFile(response, imgFile);
    }

    private void responseFile(HttpServletResponse response, File imgFile) {
        try {
            FileInputStream is = new FileInputStream(imgFile);
            ServletOutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            while(is.read(buffer) != -1){
                os.write(buffer);
            }
            os.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
